/**
 * addRepairType       添加报修类型
 * updateRepairType    修改报修类型信息
 * deleteRepairType    删除报修类型
 */
const repairStatement = require("../../common/sql_sentences/repair")
const repairTypeStatement = require("../../common/sql_sentences/repair_type")

exports.addRepairType = async (req, res) => {
  const data = req.body
  try {
    // 添加报修类型
    const sqlStr = repairTypeStatement.insert(data)
    const results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("添加报修类型失败！", 10005)
    return res.successSend("添加报修类型成功！")
  } catch (error) {
    res.errSend(error)
  }
}

exports.updateRepairType = async (req, res) => {
  try {
    const data = req.body
    // 修改报修类型信息
    sqlStr = repairTypeStatement.idUpdate(data, data.id)
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1)
      return res.successSend("修改报修类型信息失败！", 10005)
    return res.successSend("修改报修类型信息成功！")
  } catch (error) {
    res.errSend(error)
  }
}

exports.deleteRepairType = async (req, res) => {
  const id = req.params.id
  try {
    // 查询是否有子类型
    let sqlStr = repairTypeStatement.select({ pid: id })
    let results = await RunSQL(sqlStr)
    console.log(results)
    if (results[0]?.id) return res.successSend("删除报修类型失败!该类型存在子类型！", 10005)

    // 获取属于该类型的报修单数量
    sqlStr = repairStatement.selectCount({ type_id: id }) + 'and state < 6'
    console.log(sqlStr)
    results = await RunSQL(sqlStr)
    if (results[0].total) return res.successSend("删除报修类型失败!有进行中的报修单报属于该修类型！", 10005)

    // 删除报修类型
    sqlStr = repairTypeStatement.delete(id)
    console.log(sqlStr)
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("删除报修类型失败！", 10005)
    return res.successSend("删除报修类型信息成功！")
  } catch (error) {
    res.errSend(error)
  }
}
